import { webSocketConfig } from "../db.js";
import WebSocket, { WebSocketServer } from "ws";
import {
  addMessage,
  getAllMessage,
} from "./action.js";
function createWebSocketServer() {
  const wsServer = new WebSocketServer({
    port: webSocketConfig.port,
  });
  let clients = new Set(); // 用于存储所有连接的客户端
  wsServer.on("connection", async (client, req) => {
    const ip =
      req.socket.remoteAddress == "::1"
        ? "127.0.0.1"
        : req.socket.remoteAddress.replace("::ffff:", "");
    // console.log('ip:', req.socket.remoteAddress);
    const port = req.socket.remotePort;
    console.log(`Client${ip} connected.`);
    clients.add({
      client: client, // 存储客户端
      ip: ip, // 存储客户端的IP地址
    }); // 将新连接的客户端添加到列表中
    let param = {
      ip: ip,
      message: `${ip}加入服务器！`,
      time: getCurrentTime(),
      type: "0",
    };
    try {
      await addMessage(param);
    } catch (error) {
      console.log("addMessage error: ", error);
      throw error;
    }
    // 连接数返回一次全体消息
    const messages = await getAllMessage(); // 调用封装的数据库查询函数
    const ips = [...clients].map((c) => c.ip);
    clients.forEach((c) => {
      if (c.client.readyState === WebSocket.OPEN) {
        // 确保客户端仍然连接着
        let obj = {
          messages: messages,
          ip: c.ip,
          ips: ips,
          type: "all",
        };
        c.client.send(JSON.stringify(obj));
      }
    }); // 将消息发送给所有客户端
    client.on("message", async (message) => {
      let msgStr = Buffer.isBuffer(message)
        ? JSON.parse(message.toString())
        : message;
      // console.log('msgStr: ',msgStr);
      if (msgStr.type === "message") {
        try {
          await addMessage({
            ip: ip,
            message: msgStr.msg,
            time: getCurrentTime(),
            type: "1",
          });
        } catch (error) {
          console.log("addMessage error: ", error);
        }
        const messages = await getAllMessage(); // 调用封装的数据库查询函数
        const ips = [...clients].map((c) => c.ip);
        clients.forEach((c) => {
          if (c.client.readyState === WebSocket.OPEN) {
            // 确保客户端仍然连接着
            let obj = {
              messages: messages,
              ip: c.ip,
              ips: ips,
              type: "all",
            };
            c.client.send(JSON.stringify(obj));
          }
        }); // 将消息发送给所有客户端
      } else if (msgStr.type === "file") {
        const { target, fileName, fileType, fileData } = JSON.parse(msgStr.msg);
        const targetClient = [...clients].find((c) => c.ip === target);

        if (targetClient && targetClient.client.readyState === WebSocket.OPEN) {
          targetClient.client.send(
            JSON.stringify({
              type: "file",
              sender: ip,
              fileName,
              fileType,
              fileData,
            })
          );
        } else {
          // 可选：通知发送方目标不在线
          // client.send(
          //   JSON.stringify({
          //     type: "fileError",
          //     message: `目标客户端 ${target} 不在线`,
          //   })
          // );
        }
      }
    });

    client.on("close", async () => {
      console.log(`Client${ip} disconnected.`);
      let param = {
        ip: ip,
        message: `${ip}退出服务器！`,
        time: getCurrentTime(),
        type: "0",
      };
      const clientsArray = Array.from(clients);
      clients = new Set(clientsArray.filter((c) => c.ip !== ip));

      await addMessage(param);
      const messages = await getAllMessage(); // 调用封装的数据库查询函数
      const ips = [...clients].map((c) => c.ip);
      clients.forEach((c) => {
        if (c.client.readyState === WebSocket.OPEN) {
          // 确保客户端仍然连接着
          let obj = {
            messages: messages,
            ip: c.ip,
            ips: ips,
            type: "all",
          };
          c.client.send(JSON.stringify(obj));
        }
      }); // 将消息发送给所有客户端
    });
  });
  console.log(`WebSocket server is running on port ${webSocketConfig.port}...`);
  return wsServer;
}
function getCurrentTime() {
  const now = new Date();
  const date = [
    now.getFullYear(),
    now.getMonth() + 1, // 去除 padStart(2, '0')，不再补零
    now.getDate().toString().padStart(2, "0"),
  ].join("/");

  const time = [
    now.getHours().toString().padStart(2, "0"),
    now.getMinutes().toString().padStart(2, "0"),
    now.getSeconds().toString().padStart(2, "0"),
  ].join(":");

  return `${date} ${time}`;
}
export default createWebSocketServer;
